package me.magicall.test.backup;

import java.util.Collection;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import me.magicall.util.kit.Kits;

public class EmailUtil {

	/**
	 * 发送电子邮件
	 * 
	 * @param message
	 * @param title
	 * @param emails
	 */
	public static void sendMail(String message, final String title, final String... emails) {
		try {
			if (Kits.STR.isEmpty(message)) {
				message = "EMPTY BODY"; // 如果邮件内容为空，会被认为是SPAM，所以还是写一句吧
			}
			final Authenticator auth = new Authenticator() {

				@Override
				public PasswordAuthentication getPasswordAuthentication() {
					final String username = "opivas";
					final String pwd = "123456";
					return new PasswordAuthentication(username, pwd);
				}
			};
			final Properties mailProps = new Properties();
			mailProps.put("mail.smtp.user", "opivas@163.com");
			mailProps.put("mail.smtp.host", "smtp.163.com");
			mailProps.put("mail.smtp.auth", "true");
			mailProps.put("username", "opivas");
			mailProps.put("password", "123456");

			final Session mailSession = Session.getDefaultInstance(mailProps, auth);
			final MimeMessage mimeMessage = new MimeMessage(mailSession);
			final Address[] emailAddresses = new Address[emails.length];
			int i = 0;
			for (final String email : emails) {
				emailAddresses[i++] = new InternetAddress(email);
			}
			mimeMessage.setFrom(new InternetAddress("opivas@163.com"));
			mimeMessage.setRecipients(Message.RecipientType.TO, emailAddresses);
			mimeMessage.setSubject(title);
			final MimeMultipart multi = new MimeMultipart();
			final BodyPart textBodyPart = new MimeBodyPart();
			textBodyPart.setText(message);
			multi.addBodyPart(textBodyPart);
			mimeMessage.setContent(multi);
			mimeMessage.saveChanges();
			Transport.send(mimeMessage);
		} catch (final Throwable e) {
			e.printStackTrace();
		}
	}

	/**
	 * 用音乐的邮箱发送（html）电子邮件 调用 {@link #sendRenrenMailHtmlByEncode(String, String, String, String, String...)}
	 * 
	 * @param message
	 * @param title
	 * @param emails
	 */
	public static void sendMailHtml(final String message, final String title, final String... emails) {
		// try {
		// if (VerifyUtil.isEmpty(message)) {
		// message = "EMPTY BODY"; // 如果邮件内容为空，会被认为是SPAM，所以还是写一句吧
		// }
		// final Authenticator auth = new Authenticator() {
		//
		// @Override
		// public PasswordAuthentication getPasswordAuthentication() {
		// final String username = "opivas";
		// final String pwd = "123456";
		// return new PasswordAuthentication(username, pwd);
		// }
		// };
		// final Properties mailProps = new Properties();
		// mailProps.put("mail.smtp.user", "opivas@163.com");
		// mailProps.put("mail.smtp.host", "smtp.163.com");
		// mailProps.put("mail.smtp.auth", "true");
		// mailProps.put("username", "opivas");
		// mailProps.put("password", "123456");
		//
		// final Session mailSession = Session.getDefaultInstance(mailProps,
		// auth);
		// final MimeMessage mimeMessage = new MimeMessage(mailSession);
		// final Address[] emailAddresses = new Address[emails.length];
		// int i = 0;
		// for (final String email : emails) {
		// emailAddresses[i++] = new InternetAddress(email);
		// }
		// mimeMessage.setFrom(new InternetAddress("opivas@163.com"));
		// mimeMessage.setRecipients(Message.RecipientType.TO, emailAddresses);
		// mimeMessage.setSubject(title);
		// final MimeMultipart multi = new MimeMultipart();
		// final BodyPart textBodyPart = new MimeBodyPart();
		// textBodyPart.setContent(message,
		// "text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
		// multi.addBodyPart(textBodyPart);
		// mimeMessage.setContent(multi);
		// mimeMessage.saveChanges();
		// Transport.send(mimeMessage);
		// } catch (final Throwable e) {
		// e.printStackTrace();
		// }

		// ///////////////////////////////////////////////////
		sendRenrenMailHtmlByEncode("music@renren-inc.com", message, title, "gb2312", emails);
	}

	/**
	 * 用renren-inc的邮箱发送邮件，不需要密码
	 * 
	 * @param from
	 *            发件人
	 * @param message
	 *            邮件内容
	 * @param title
	 *            标题
	 * @param encode
	 *            邮件编码 用小写 例：{@code "utf-8"}
	 * @param emails
	 *            收件人列表
	 */
	public static void sendRenrenMailHtmlByEncode(final String from, String message, final String title, final String encode, final String... emails) {
		try {
			if (Kits.STR.isEmpty(message)) {
				message = "EMPTY BODY"; // 如果邮件内容为空，会被认为是SPAM，所以还是写一句吧
			}
			final Properties mailProps = new Properties();
			mailProps.put("mail.smtp.user", from);
			mailProps.put("mail.smtp.host", "mail.renren-inc.com");
			final Session mailSession = Session.getDefaultInstance(mailProps);
			final MimeMessage mimeMessage = new MimeMessage(mailSession);
			final Address[] emailAddresses = new Address[emails.length];
			int i = 0;
			for (final String email : emails) {
				emailAddresses[i++] = new InternetAddress(email);
			}
			mimeMessage.setFrom(new InternetAddress(from));
			mimeMessage.setRecipients(Message.RecipientType.TO, emailAddresses);
			mimeMessage.setSubject(title);
			final MimeMultipart multi = new MimeMultipart();
			final BodyPart textBodyPart = new MimeBodyPart();
			textBodyPart.setContent(message, "text/html;charset=" + encode + "");// 给BodyPart对象设置内容和格式/编码方式
			multi.addBodyPart(textBodyPart);
			mimeMessage.setContent(multi);
			mimeMessage.saveChanges();
			Transport.send(mimeMessage);
		} catch (final Throwable e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送带有附件的电子邮件
	 * 
	 * @param message
	 * @param title
	 * @param emails
	 */
	public static void sendMailWithAttachment(String message, final String title, final Collection<String> fileNames, final String... emails) {
		try {
			if (Kits.STR.isEmpty(message)) {
				message = "EMPTY BODY"; // 如果邮件内容为空，会被认为是SPAM，所以还是写一句吧
			}
			final Authenticator auth = new Authenticator() {

				@Override
				public PasswordAuthentication getPasswordAuthentication() {
					final String username = "opivas";
					final String pwd = "123456";
					return new PasswordAuthentication(username, pwd);
				}
			};
			final Properties mailProps = new Properties();
			mailProps.put("mail.smtp.user", "opivas@163.com");
			mailProps.put("mail.smtp.host", "smtp.163.com");
			mailProps.put("mail.smtp.auth", "true");
			mailProps.put("username", "opivas");
			mailProps.put("password", "123456");

			final Session mailSession = Session.getDefaultInstance(mailProps, auth);
			final MimeMessage mimeMessage = new MimeMessage(mailSession);
			final Address[] emailAddresses = new Address[emails.length];
			int i = 0;
			for (final String email : emails) {
				emailAddresses[i++] = new InternetAddress(email);
			}
			mimeMessage.setFrom(new InternetAddress("opivas@163.com"));
			mimeMessage.setRecipients(Message.RecipientType.TO, emailAddresses);
			mimeMessage.setSubject(title);
			final MimeMultipart multi = new MimeMultipart();
			final BodyPart textBodyPart = new MimeBodyPart();
			textBodyPart.setContent(message, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式
			if (fileNames != null) {
				for (final String fileName : fileNames) {
					try {
						final BodyPart attachment = new MimeBodyPart();
						final FileDataSource fds = new FileDataSource(fileName); // 得到数据源
						attachment.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
						attachment.setFileName(fds.getName()); // 得到文件名同样至入BodyPart
						multi.addBodyPart(attachment);
					} catch (final Throwable e) {
						e.printStackTrace();
					}
				}
			}
			multi.addBodyPart(textBodyPart);
			mimeMessage.setContent(multi);
			mimeMessage.saveChanges();
			Transport.send(mimeMessage);
		} catch (final Throwable e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加密邮件地址
	 * 
	 * @param fmail
	 *            邮件地址明文
	 * @return 邮件地址密文
	 */
	public static String getUserMailByStar(final String fmail) {
		if (fmail == null || fmail.length() < 1) {
			return null;
		}
		final int pos = fmail.indexOf('@');
		final StringBuffer tmp = new StringBuffer();
		for (int i = 0; i < fmail.length(); i++) {
			if (i < 2 || i > pos) {
				tmp.append(fmail.charAt(i));
			} else {
				if (i == pos) {
					tmp.append("@");
				} else if (i == pos - 1) {
					tmp.append(fmail.charAt(i));
				} else {
					tmp.append("*");
				}
			}
		}
		return tmp.toString();
	}

}
